package com.example.iorder.reservation;

import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.iorder.R;
import com.example.iorder.util.TextFormatter;

public class SelectDateAndTime extends Activity {
	private TextView selectedDateView, selectedTimeView;
	private Calendar selectedDate;
	static final int DATE_DIALOG_ID = 999;
	static final int TIME_DIALOG_ID = 998;
	Toast messenger = null;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reservation_select_date_time);
		
		// Set the current date as default value
		selectedDateView = (TextView) findViewById(R.id.reservationDate);
		selectedDate = Calendar.getInstance();
		int currentYear = selectedDate.get(Calendar.YEAR);
		int currentMonth = selectedDate.get(Calendar.MONTH);
		int currentDay = selectedDate.get(Calendar.DAY_OF_MONTH);
		selectedDateView.setText(formatSelectedDate(currentYear, currentMonth, currentDay));
		
		// Set the current time as default value
		selectedTimeView = (TextView) findViewById(R.id.reservationTime);
		int currentHour = selectedDate.get(Calendar.HOUR_OF_DAY);
		int currentMinute = selectedDate.get(Calendar.MINUTE);
		selectedTimeView.setText(formatSelectedTime(currentHour, currentMinute));
		
		setupButtons();
	}
	
	private void setupButtons() {
		ImageButton showDatePickerButton = (ImageButton) findViewById(R.id.reservationDateButton);
		showDatePickerButton.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		
		ImageButton showTimePickerButton = (ImageButton) findViewById(R.id.reservationTimeButton);
		showTimePickerButton.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});
		
		Button confirmDateAndTimeButton = (Button) findViewById(R.id.confirmDateTime);
		confirmDateAndTimeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SelectDateAndTime.this, TableReservation.class);
				Bundle bundle = getIntent().getExtras();
				int restId = bundle.getInt(getResources().getString(R.string.key_restaurant_id));
				int random = restId + 5;
				Bundle extraInfo = new Bundle(getIntent().getExtras());
				int[] arrayOfSelectedDate = new int[] {
						selectedDate.get(Calendar.YEAR),
						selectedDate.get(Calendar.MONTH),
						selectedDate.get(Calendar.DAY_OF_MONTH),
						selectedDate.get(Calendar.HOUR_OF_DAY),
						selectedDate.get(Calendar.MINUTE)
				};
				extraInfo.putIntArray(getResources().getString(R.string.key_date_time), arrayOfSelectedDate);
				intent.putExtras(extraInfo);
				startActivity(intent);
			}
		});
	}
 
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case DATE_DIALOG_ID:
				// set date picker as current date
				final int minYear = selectedDate.get(Calendar.YEAR);
				final int minMonth = selectedDate.get(Calendar.MONTH);
				final int minDay = selectedDate.get(Calendar.DAY_OF_MONTH);
				DatePickerDialog dialog = new DatePickerDialog(this, datePickerListener, minYear, minMonth, minDay);
				configureDatePickerDialog(dialog);
				return dialog;
			case TIME_DIALOG_ID:
				// set time picker as current time
				int hour = selectedDate.get(Calendar.HOUR_OF_DAY);
				int minutes = selectedDate.get(Calendar.MINUTE);
				return new TimePickerDialog(this, timePickerListener, hour, minutes, true);
		}
		return null;
	}
 
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
			selectedDate.set(selectedYear, selectedMonth, selectedDay);
			selectedDateView.setText(formatSelectedDate(selectedYear, selectedMonth, selectedDay));
		}
	};
	
	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			selectedDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
			selectedDate.set(Calendar.MINUTE, minute);
			selectedTimeView.setText(formatSelectedTime(hourOfDay, minute));
		}
	};
	
	private void configureDatePickerDialog(DatePickerDialog dialog) {
		dialog.setTitle(R.string.lbl_reservation_date);
		final GregorianCalendar today = new GregorianCalendar();
		final int minYear = today.get(GregorianCalendar.YEAR);
		final int minMonth = today.get(GregorianCalendar.MONTH);
		final int minDay = today.get(GregorianCalendar.DAY_OF_MONTH);
		Field mDatePickerField = null;
		try {
			mDatePickerField = dialog.getClass().getDeclaredField("mDatePicker");
			mDatePickerField.setAccessible(true);
			final DatePicker mDatePickerInstance = (DatePicker) mDatePickerField.get(dialog);
			mDatePickerInstance.init(minYear, minMonth, minDay, new OnDateChangedListener() {
				@Override
				public void onDateChanged(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
					GregorianCalendar selectedDate = new GregorianCalendar(selectedYear, selectedMonth, selectedDay);
					GregorianCalendar maxDate = new GregorianCalendar(minYear, minMonth + 1, minDay);
					if (selectedDate.before(today)) {
						String message = "Datum mag niet eerder zijn dan: \n" + minDay + " - " + (minMonth + 1) + " - " + minYear;
						showMessage(message);
						mDatePickerInstance.init(minYear, minMonth, minDay, this);
					} else if (selectedDate.after(maxDate)) {
						String message = "Datum mag niet later zijn dan: \n" + minDay + " - " + (minMonth + 2) + " - " + minYear;
						showMessage(message);
						mDatePickerInstance.init(minYear, minMonth + 1, minDay, this);
					}
				}
			});
		} catch (NoSuchFieldException e) {
			Log.e("DatePickerDialog", e.getMessage());
		} catch (IllegalAccessException e) {
			Log.e("DatePickerDialog", e.getMessage());
		} catch (IllegalArgumentException e) {
			Log.e("DatePickerDialog", e.getMessage());
		}
	}
	
	private void showMessage(String message) {
		if (messenger != null && messenger.getView().getWindowVisibility() == View.VISIBLE) {
			messenger.cancel();
			messenger = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG);
			messenger.show();
		} else {
			messenger = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG);
			messenger.show();
		}
	}
	
	private String formatSelectedDate(int year, int month, int day) {
		String formattedMonth = TextFormatter.getMonthAsText(month);
		String formattedDate = "Datum: " + day + " " + formattedMonth + " " + year;
		return formattedDate;
	}
	
	private String formatSelectedTime(int hour, int minute) {
		String formattedTime = "Tijd: " + hour + " : " + minute;
		if (minute == 0)
			formattedTime += "0";
		return formattedTime;
	}
}
